<?php
/**
 * Created by PhpStorm.
 * User: zjw
 * Date: 2018/10/18
 * Time: 下午1:36
 */

namespace common\service;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

class HttpRequestService
{
    public static function sendRequest($url, $method, $data)
    {
        $client = new Client();
        try {
            $responses = $client->request(
                $method,
                $url,
                [
                    'headers' => [
                        'Content-Type' => 'application/json;charset=utf-8',
                    ],
                    'body' => json_encode($data),
                ]
            );
            return $responseData = json_decode($responses->getBody()->getContents());
        } catch (\GuzzleHttp\Exception\ServerException $e) {
            throw  $e;
        } catch (RequestException $e) {
            throw  $e;
        } catch (\Exception $e) {
            throw  $e;
        }
    }

    public static function sendGetRequest($url)
    {
        $client = new Client();
        try {
            $responses = $client->request(
                "GET",
                $url,
                [
                    'headers' => [
                        'Content-Type' => 'application/json;charset=utf-8',
                    ]
                ]
            );
            return $responseData = json_decode($responses->getBody()->getContents());
        } catch (\GuzzleHttp\Exception\ServerException $e) {
            throw  $e;
        } catch (RequestException $e) {
            throw  $e;
        } catch (\Exception $e) {
            throw  $e;
        }
    }
}
